package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author Lorenzo Nuvoletta
	 */
	public class Main extends Sprite 
	{
		private var div:int;
		private var queue:Array = new Array();
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			div = 30;
			
			var W:Number = stage.stageWidth / div;
			var H:Number = stage.stageHeight / div;
			for (var i:int = 0; i < div*div; i++) {
				var COL:int = i % div;
				var ROW:int = i / div;
				queue.push( new Rectangle( COL * W, ROW * H, W, H) );
			}
			condenseRects(5);
			showRects();
		}
		
		private function showRects():void 
		{
			for (var i:int = 0; i < queue.length; i++) {
				this.graphics.beginFill(Math.random() * 0xAAAAAA, 1);
				this.graphics.drawRect(queue[i].x, queue[i].y, queue[i].width, queue[i].height);
				this.graphics.endFill();
			}
		}
		
		
		private function condenseRects(n:Number):void 
		{			
			var condesnable:Array = new Array();
			for (var i:int = 0; i < div; i++) {
				condesnable.push( new Array() );
				for (var j:int = 0; j < div; j++) {
					if (i >= div - n || j >= div - n) {
						condesnable[i].push(false);
					}
					else condesnable[i].push(true);					
				}	
			}			
			
			var rectsToRemove:Array = new Array();
			for (i = 0; i < div; i++) {				
				for (j = 0; j < div; j++) {
					if (condesnable[i][j] && Math.random() < .3) {
						
						var rectangles:Array = new Array();
						trace("-----------");
						var side:int = (n + n + 1);
						for (var l:int = 0; l < side * side; l++) {
							var newI:int = i - n + (l % side);
							var newJ:int = j - n + int(l / side);
							if ( condesnable[newI] && condesnable[newI].hasOwnProperty(newJ) ) {								
								condesnable[newI][newJ] = false;
								if ( newI >= i && newJ >= j ) {
									trace(newI, newJ, (newJ * div) + newI, "DIV:"+div);
									rectsToRemove.push((newJ * div) + newI);
									rectangles.push( queue[ (newJ*div) + newI ] );
								}
							}								
						}
						
						if(rectangles.length>0){
							trace(rectangles[0]);
							var finalRect:Rectangle = rectangles[0];							
							for (var k:int = 1; k < rectangles.length; k++) {
								trace(rectangles[k]);
								finalRect = finalRect.union(rectangles[k]);
							}
							queue.push(finalRect);
						}
					}
					
				}	
			}
			
			for (k = 0; k < rectsToRemove.length; k++) {
				queue[rectsToRemove[k]] = null;				
			}
			
			for (k = 0; k < queue.length; k++) {
				if (!queue[k]) {
					queue.splice(k, 1);
					k--;
				}
			}			
			
		}
		
		
		
	}
	
}